<template>
  <el-dialog
    :model-value="deploymentDetailsDialogVisible"
    title="详情"
    width="80%"
    @close="handleClose"
  >
      <el-row :gutter="20">
        <el-col :span="12">
           <!--基本信息-->
          <el-card>
            <template #header>
              <div class="card-header">
                <span>基本信息</span>
              </div>
            </template>
            名称: <el-tag type="info">{{deploy_info.name}}</el-tag>
            <hr>
            命名空间: <el-tag type="info">{{deploy_info.namespace}}</el-tag>
            <hr>
            副本数量: <el-tag type="success">期望{{deploy_info.replicas}}</el-tag> / <el-tag type="warning">可用{{deploy_info.available_replicas}}</el-tag>
            <hr>
            镜像: <el-tag type="info" v-for="(key,index) in containers">{{key.image}}</el-tag>
            <hr>
            标签选择器: <el-tag  type="info" v-for="(value,key,index) in deploy_info.selector">{{ key }}:{{value}}</el-tag>
            <hr>
            创建时间: <el-tag type="info">{{deploy_info.create_time}}</el-tag>
            <hr>
          </el-card>
           <!--Service-->
          <el-card style="margin-top: 20px">
            <template #header>
              <div class="card-header">
                <span>Service</span>
              </div>
            </template>
            <div v-if="service.length > 0">
              类型: <el-tag type="info" v-for="(key,index) in service">{{key.type}}</el-tag>
              <hr>
              ClusterIP: <el-tag type="info" v-for="(key,index) in service">{{key.cluster_ip}}</el-tag>
              <hr>
              访问端口:
              <hr>
                <el-table :data="ports" border
                          :cell-style="{textAlign: 'center'}"
                          :header-cell-style="{background: '#F8F8F8',textAlign: 'center' }" style="width: 100%">
                  <el-table-column prop="name" label="名称"  />
                  <el-table-column prop="port" label="服务端口"  />
                  <el-table-column prop="target_port" label="容器端口" />
                  <el-table-column prop="protocol" label="协议" />
                  <el-table-column prop="node_port" label="NodePort" />
                </el-table>
           </div>
            <el-tag type="info" v-else>此处显示通过 Deployment 标签筛选出的Service，但是您并未定义！</el-tag>
          </el-card>
           <!--Ingress-->
          <el-card style="margin-top: 20px">
            <template #header>
              <div class="card-header">
                <span>Ingress</span>
              </div>
            </template>
            <div v-if="rules != null">
              <template v-for="(key,index) in rules">
                <span type="info" v-if="key.tls != null">
                域名:   <el-tag type="primary" >https://{{key.host}}</el-tag>
                </span>
                <span type="info" v-else>
                域名:  <el-tag type="primary" >http://{{key.host}}</el-tag>
                </span>
              </template>
              <hr>
              访问端口:
              <hr>
                <el-table :data="rules" border
                          :header-cell-style="{background: '#F8F8F8',textAlign: 'center' }"
                          :cell-style="{textAlign: 'center'}"
                          style="width: 100%">
                  <el-table-column prop="path" label="路由规则"  />
                  <el-table-column prop="service_name" label="服务名称"  />
                  <el-table-column prop="service_port" label="服务端口" />
                  <el-table-column prop="protocol" label="HTTPS" >
                     <template v-slot="scope">
                        <span v-if="ingress.tls === null">未启用</span>
                        <span v-else>已启用</span>
                      </template>
                  </el-table-column>
                </el-table>
           </div>
            <el-tag type="info" v-else>此处显示是通过 Ingress 后端与上面 Service 匹配的 Ingress，但是您并未定义！</el-tag>
          </el-card>
        </el-col>
        <el-col :span="12">
          <!--更多信息-->
          <el-card >
            <template #header>
             <div class="card-header">
                <span>更多信息</span>
              </div>
            </template>
            滚动更新:
            <div v-if="rolling_update.max_surge || rolling_update.max_unavailable != null">
              <br>
              <el-tag type="info">最大超出副本数:{{rolling_update.max_surge}}</el-tag>
              <el-tag type="info" style="margin-left: 5px;">最大不可用副本数:{{rolling_update.max_unavailable}}</el-tag>
            </div>
            <el-tag type="info" v-else>此处显示是滚动更新配置，但是您并未定义！</el-tag>
            <hr>
            数据卷:
            <div v-if="volumes.length > 0">
              <br>
              <template v-for="(key,index) in volumes">
                <span type="info" v-if="key.config_map != null">
                 <el-tag type="info">卷名称:{{key.config_map.name}}</el-tag>
                 <el-tag type="info">卷类型:{{key.config_map.type}}</el-tag>
                </span>
                <span type="info" v-else-if="key.secret != null">
                 <el-tag type="info">卷名称:{{key.secret.name}}</el-tag>
                 <el-tag type="info">卷类型:{{key.secret.type}}</el-tag>
                </span>
                <span type="info" v-else-if="key.empty_dir != null">
                 <el-tag type="info">卷名称:{{key.empty_dir.name}}</el-tag>
                 <el-tag type="info">卷类型:{{key.empty_dir.type}}</el-tag>
                </span>
                <span type="info" v-else-if="key.host_path != null">
                 <el-tag type="info">卷名称:{{key.host_path.name}}</el-tag>
                 <el-tag type="info">卷类型:{{key.host_path.type}}</el-tag>
                </span>
                <span type="info" v-else-if="key.config_map != null">
                 <el-tag type="info">卷名称:{{key.downward_api.name}}</el-tag>
                 <el-tag type="info">卷类型:{{key.downward_api.type}}</el-tag>
                </span>
                <span type="info" v-else-if="key.glusterfs != null">
                 <el-tag type="info">卷名称:{{key.glusterfs.name}}</el-tag>
                 <el-tag type="info">卷类型:{{key.glusterfs.type}}</el-tag>
                </span>
                <span type="info" v-else-if="key.cephfs != null">
                 <el-tag type="info">卷名称:{{key.cephfs.name}}</el-tag>
                 <el-tag type="info">卷类型:{{key.cephfs.type}}</el-tag>
                </span>
                <span type="info" v-else-if="key.rbd != null">
                 <el-tag type="info">卷名称:{{key.rbd.name}}</el-tag>
                 <el-tag type="info">卷类型:{{key.rbd.type}}</el-tag>
                </span>
                <span type="info" v-else-if="key.persistent_volume_claim != null">
                 <el-tag type="info">卷名称:{{key.persistent_volume_claim.name}}</el-tag>
                 <el-tag type="info">卷类型:{{key.persistent_volume_claim.type}}</el-tag>
                </span>
                <span type="info" v-else-if="key.unknown != null">
                 <el-tag type="info">未知:{{key.unknown}}</el-tag>
                </span>
              </template>
            </div>
            <el-tag type="info" v-else>此处显示是数据卷配置，但是您并未定义！</el-tag>
            <hr>
            污点容忍:
            <div v-if="tolerations != null">
            <br>
             <template v-for="(key,index) in tolerations">
               <el-tag type="info">key:{{key.key}}</el-tag>
               <el-tag type="info">operator:{{key.operator}}</el-tag>
               <el-tag type="info">effect:{{key.effect}}</el-tag>
               <el-tag type="info">容忍时间:{{key.toleration_seconds}}</el-tag>
               <br>
             </template>
            </div>
             <el-tag type="info" v-else>此处显示是污点容忍配置，但是您并未定义！</el-tag>
            <hr>
          </el-card>
          <!--容器配置-->
          <el-card style="margin-top: 20px">
          <template #header>
           <div class="card-header">
              <span>容器配置</span>
            </div>
          </template>
            容器名: <el-tag type="info" v-for="(key,index) in containers">{{key.name}}</el-tag>
            <hr>
            变量:
            <div v-if="env != null">
             <br>
             <template v-for="(key,index) in env">
               <span v-if="key.value != null">
                   <el-tag type="info">来源：自定义</el-tag>
                   <el-tag type="info">名称:{{key.name}}</el-tag>
                   <el-tag type="info">值:{{key.value}}</el-tag>
               </span>
               <span v-if="key.value_from != null">
                  <template v-if="key.value_from.config_map_key_ref != null">
                    <el-tag type="info">来源：configmap /:{{key.value_from.config_map_key_ref.name}}</el-tag>
                    <el-tag type="info">名称：{{key.name}}</el-tag>
                  </template>
                  <template v-else-if="key.value_from.secret_key_ref != null">
                    <el-tag type="info">来源：secret /:{{key.value_from.secret_key_ref.name}}</el-tag>
                    <el-tag type="info">名称：{{key.name}}</el-tag>
                  </template>
                  <template v-else-if="key.value_from.field_ref != null">
                    <el-tag type="info">Pod属性：secret /:{{key.value_from.field_ref.name}}</el-tag>
                    <el-tag type="info">名称：{{key.name}}</el-tag>
                  </template>
               </span>
               <br>
             </template>
            </div>
            <el-tag type="info" v-else>此处显示是变量配置，但是您并未定义！</el-tag>
            <hr>
            端口:
            <div v-if="container_ports != null">
             <br>
             <template v-for="(key,index) in container_ports">
               <el-tag type="info">名称:{{key.name}}</el-tag>
               <el-tag type="info">容器端口:{{key.container_port}}</el-tag>
               <el-tag type="info">协议:{{key.protocol}}</el-tag>
               <br>
             </template>
            </div>
            <el-tag type="info" v-else>此处显示是端口配置，但是您并未定义！</el-tag>
            <hr>
            资源分配:
                 <br>
                 <br>
                 请求:
                 <template v-for="(key,index) in resources" :key="index">
                   <el-tag type="info" v-if="key.requests.cpu != null">CPU:{{key.requests.cpu}}</el-tag>
                   <el-tag type="info" v-else>CPU:未定义</el-tag>
                   <el-tag type="info" v-if="key.requests.memory != null">内存:{{key.requests.memory }}</el-tag>
                   <el-tag type="info" v-else>内存:未定义</el-tag>
                 </template>
                 <br>
                 限制:
                 <template v-for="(key,index) in resources" :key="index">
                   <el-tag type="info" v-if="key.limits.cpu != null">CPU:{{key.limits.cpu}}</el-tag>
                   <el-tag type="info" v-else>CPU:未定义</el-tag>
                   <el-tag type="info" v-if="key.limits.memory != null">内存:{{key.limits.memory }}</el-tag>
                   <el-tag type="info" v-else>内存:未定义</el-tag>
                 </template>
                 <hr>
             健康检查(就绪检查):
             <div v-if="readiness_probe != null">
                 <br>
                 <span v-for="(key,index) in readiness_probe" :key="index">
                   <template v-if="key.http_get">
                     <el-tag type="info">类型:{{key.http_get}}</el-tag>
                     <el-tag type="info">URL:{{key.path}}</el-tag>
                     <el-tag type="info">端口:{{key.port}}</el-tag>
                     <el-tag type="info">协议:{{key.scheme}}</el-tag>
                     <el-tag type="info">初始延迟检查时间(s):{{key.initial_delay_seconds}}</el-tag>
                     <el-tag type="info">周期间隔(s):{{key.period_seconds}}</el-tag>
                   </template>
                   <template v-else-if="key.tcp_socket">
                     <el-tag type="info">类型:{{key.tcp_socket}}</el-tag>
                     <el-tag type="info">端口:{{key.port}}</el-tag>
                     <el-tag type="info">初始延迟检查时间(s):{{key.initial_delay_seconds}}</el-tag>
                     <el-tag type="info">周期间隔(s):{{key.period_seconds}}</el-tag>
                   </template>
                 </span>
             </div>
             <el-tag type="info" v-else>此处显示是健康检查配置，但是您并未定义！</el-tag>
             <hr>
            健康检查(存活检查):
             <div v-if="liveness_probe != null">
                 <br>
                 <span v-for="(key,index) in readiness_probe" :key="index">
                   <template v-if="key.http_get">
                     <el-tag type="info">类型:{{key.http_get}}</el-tag>
                     <el-tag type="info">URL:{{key.path}}</el-tag>
                     <el-tag type="info">端口:{{key.port}}</el-tag>
                     <el-tag type="info">协议:{{key.scheme}}</el-tag>
                     <el-tag type="info">初始延迟检查时间(s):{{key.initial_delay_seconds}}</el-tag>
                     <el-tag type="info">周期间隔(s):{{key.period_seconds}}</el-tag>
                   </template>
                   <template v-else-if="key.tcp_socket">
                     <el-tag type="info">类型:{{key.tcp_socket}}</el-tag>
                     <el-tag type="info">端口:{{key.port}}</el-tag>
                     <el-tag type="info">初始延迟检查时间(s):{{key.initial_delay_seconds}}</el-tag>
                     <el-tag type="info">周期间隔(s):{{key.period_seconds}}</el-tag>
                   </template>
                 </span>
             </div>
             <el-tag type="info" v-else>此处显示是健康检查配置，但是您并未定义！</el-tag>
            <hr>
            数据卷:
              <div v-if="volume_mounts != null">
               <br>
               <template v-for="(key,index) in volume_mounts">
                  <el-tag type="info">名称:{{key.name}}</el-tag>
                  <el-tag type="info">挂载点:{{key.mount_path}}</el-tag>
                  <el-tag type="info">子路径:{{key.sub_path}}</el-tag>
                  <el-tag type="info">只读:{{key.read_only}}</el-tag>
                 <br>
               </template>
              </div>
              <el-tag type="info" v-else>此处显示是变量配置，但是您并未定义！</el-tag>
            <hr>
        </el-card>
        </el-col>
      </el-row>
        <!--历史发布版本-->
      <el-card style="margin-top: 20px">
        <template #header>
         <div class="card-header">
            <span>历史发布版本(ReplicaSet副本集)</span>
          </div>
        </template>
            <el-table :data="tableData" :show-overflow-tooltip="true" border style="width: 100%">
                <el-table-column prop="name" label="名称"   align="center"/>
                <el-table-column prop="namespace" label="命名空间"   align="center"/>
                <el-table-column prop="replicas" label="期望" align="center" />
                <el-table-column prop="ready_replicas" label="就绪"  align="center"/>
                <el-table-column prop="available_replicas" label="可用"  align="center"/>
                <el-table-column prop="revision" label="版本号"   align="center"/>
                <el-table-column prop="containers" label="镜像版本差异"  align="center">
                   <template v-slot="scope">
                      <el-tag size="small" type="info" v-for="(value,key) in scope.row.containers" :key="key"> {{ key }}:{{value}}</el-tag>
                   </template>
                </el-table-column>
                <el-table-column prop="create_time" label="创建时间"  align="center"/>
                <el-table-column prop="action"  label="操作" fixed="right" align="center">
                    <template v-slot="scope">
                      <el-popconfirm title="您确定要回滚到这个版本吗？"
                         @confirm="handleRollback(scope.row.namespace,scope.row.revision)">
                        <template #reference>
                          <el-button type="warning" >回滚</el-button>
                        </template>
                      </el-popconfirm>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination style="float: right"
                v-model:current-page="queryForm.pageNum"
                v-model:page-size="queryForm.pageSize"
                :page-sizes="[10, 20, 30, 40]"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
            />
        </el-card>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, watch, onMounted, defineProps, defineEmits } from 'vue';
import requestUtil from '@/util/request';
import { ElMessage } from 'element-plus';

// 定义Props
const props = defineProps({
  resource_name: {
    type: String,
    required: true,
    default: '',
  },
  resource_namespace: {
    type: String,
    required: true,
    default: '',
  },
  deploymentDetailsDialogVisible: {
    type: Boolean,
    required: true,
    default: false,
  },
});

const tableData=ref([])
const total=ref(0)
const queryForm=ref({
  pageNum:1,
  pageSize:10,
})

// 定义Ref 基本信息
const deploy_info = ref({})
const containers = ref([])
const service = ref([])
const ports = ref([])
const ingress = ref([])
const rules = ref([])
const rolling_update = ref({})
const volumes = ref([])
const tolerations = ref([])
//容器资源
const env = ref(null)
const container_ports = ref(null)
const resources = ref(null)
const liveness_probe = ref(null)
const readiness_probe = ref(null)
const volume_mounts = ref(null)


// 定义Emits
const emits = defineEmits(['update:modelValue']);

const deploymentInfo = async () => {
  let res = await requestUtil.get("workload/deployment_details", {name:props.resource_name,namespace:props.resource_namespace})
  if (res.data.code === 200) {
      //基本信息
      deploy_info.value = []
      deploy_info.value = res.data.data

      //容器信息
      containers.value = []
      containers.value = res.data.data.containers

      //service 清理上次保存的值
      service.value = []
      ports.value = []
      if (res.data.data.service.length > 0) {
        service.value = res.data.data.service
        for(let i in res.data.data.service){
          for (let n in res.data.data.service[i].ports)
          ports.value.push(res.data.data.service[i].ports[n])
        }
      }

      //ingress && rules
      ingress.value = []
      rules.value = []
      ingress.value = res.data.data.ingress
      rules.value = res.data.data.ingress.rules

      //滚动更新
      rolling_update.value = {}
      if (res.data.data.rolling_update != null){
        rolling_update.value = res.data.data.rolling_update
      }

      //清空数据卷值
      volumes.value = []
      if (res.data.data.volumes.length > 0) {
        for (let i in res.data.data.volumes )
          volumes.value.push(res.data.data.volumes[i])
      }

      //污点
      tolerations.value = []
      tolerations.value = res.data.data.tolerations

      //置空上次的数据
      env.value = null
      container_ports.value = null
      resources.value = null
      liveness_probe.value = null
      readiness_probe.value = null
      volume_mounts.value = null

      //循环读取容器配置
      const resources_list = []
      const liveness_probe_list = []
      const readiness_probe_list = []
      for (let i in res.data.data.containers){
        //变量
        if (res.data.data.containers[i].env != null){
          env.value = res.data.data.containers[i].env
        }
        //端口
        if (res.data.data.containers[i].ports != null){
          container_ports.value = res.data.data.containers[i].ports
        }
        //资源分配
        resources_list.push(res.data.data.containers[i].resources)
        resources.value = resources_list
        //健康检查
        if (res.data.data.containers[i].liveness_probe != null){
          liveness_probe_list.push(res.data.data.containers[i].liveness_probe)
          liveness_probe.value = liveness_probe_list
        }
        if (res.data.data.containers[i].readiness_probe != null){
          readiness_probe_list.push(res.data.data.containers[i].readiness_probe)
          readiness_probe.value = readiness_probe_list
        }
        //数据卷
        if (res.data.data.containers[i].volume_mounts != null){
          volume_mounts.value = res.data.data.containers[i].volume_mounts
        }
      }

  } else {
    ElMessage({
      type: 'error',
      message: res.data.msg,
    })
  }
}

const initList=async ()=>{
  //请求时追加节点名参数进去
  const tempQueryForm = {...queryForm.value, name: props.resource_name, namespace: props.resource_namespace };
  const res=await requestUtil.get("workload/replicaset_api",tempQueryForm)
  tableData.value=res.data.data
  total.value=res.data.count
}

const handleRollback = async (namespace,revision) => {
  let res = await requestUtil.post("workload/replicaset_api", {name:props.resource_name,namespace:namespace,revision:revision})
  if (res.data.code === 200) {
    ElMessage({
      type: 'success',
      message: res.data.msg,
    })
  } else {
    ElMessage({
      type: 'error',
      message: res.data.msg,
    })
  }
}


const handleSizeChange=(pageSize)=>{
  queryForm.value.pageSize=pageSize
  queryForm.value.pageNum=1
  initList()
}

const handleCurrentChange=(pageNum)=>{
  queryForm.value.pageNum=pageNum
  initList()
}

// 监听打开窗口
watch(() => props.deploymentDetailsDialogVisible, (newValue) => {
  if (newValue) {
    deploymentInfo()
    initList()
  }
});

// 关闭对话框
const handleClose = () => {
  emits('update:modelValue', false);
};

</script>

<style scoped>

</style>